package org.dragonnova.meetingapp.core.net.socket;

import org.dragonnova.meetingapp.core.message.GroupMessage;
import org.dragonnova.meetingapp.core.message.MessageBuilder;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;

/**
 * Created by Administrator on 2015/10/29 09:53.
 * Author: songxy
 * Email: thinkdata@163.com
 */
public class UdpSocket {

    /**
     * 包大小
     */
    public static final int PACKET_BUFFER_SIZE = 524288;
    private DatagramSocket mSocket;


    public UdpSocket(DatagramSocket socket) {
        mSocket = socket;
    }

    public boolean isBound() {
        return mSocket != null && mSocket.isBound();
    }

    public void sendMsgToNetwork(UdpPacket packet) throws IOException {
        mSocket.send(packet.create());
    }

    public UdpPacket receiveMsgFromNetwork(int packetBufferSize) throws IOException {
        UdpPacket packet = null;
        try {
            packet = new UdpPacket(packetBufferSize);
            DatagramPacket inPacket = packet.getPacket();
            mSocket.receive(inPacket);
            packet.setSocketAddress(inPacket.getSocketAddress());
            packet.setMessage(new MessageBuilder(new GroupMessage()).decode(inPacket.getData()));
        } catch (SocketTimeoutException e) {
            throw e;
        } catch (IOException e) {
            //throw new IOException("Receive Msg From Remote Error" + e.getMessage());
            e.printStackTrace();
        }
        return packet;
    }

    public SocketAddress getSocketInetAddress() {
        return mSocket.getRemoteSocketAddress();
    }

    public boolean isClosed() {
        return (mSocket != null && mSocket.isClosed());
    }

    public void close() {
        mSocket.close();
    }

    public DatagramSocket getSocket() {
        return mSocket;
    }
}
